package org.tostring.pork;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.inject.Inject;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.pork.domain.AccountVO;
import org.pork.domain.EmployeesPictureVO;
import org.pork.service.EmployeesPictureService;
import org.pork.util.RandomNaming;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/pictureupload")
public class EmployeesPictureControl {
	
	private static final Logger logger = Logger.getLogger(EmployeesPictureControl.class);
	
	@Inject
	EmployeesPictureService ePService;

	
	
	
	//JSP 페이지로 화면 이동
	@RequestMapping(method = RequestMethod.GET)
	public String fileUploadForm() {
		
		return "pictureupload";
		
	}

	
	
	@RequestMapping(method = RequestMethod.POST)
	public String processUpload(@RequestParam("file") MultipartFile file) throws Exception {
		
		logger.info("upload............" + file.getOriginalFilename());
		
		EmployeesPictureVO vo = new EmployeesPictureVO();
		
		
	    if(!file.isEmpty()){
	    	
	        vo.setpName(file.getOriginalFilename());
	      
	        String imgExt = vo.getpName().substring(vo.getpName().lastIndexOf(".")+1, vo.getpName().length());
	 
	        //upload 가능한 파일 타입 지정
	        if(imgExt.equalsIgnoreCase("JPG") || imgExt.equalsIgnoreCase("JPEG") || imgExt.equalsIgnoreCase("GIF")){
	        	
	        	RandomNaming rNaming = new RandomNaming();
		            
		        vo.setpRealName(rNaming.naming(imgExt));
	        	
	        	String uri = "C:/filefolder/" + vo.getpRealName();
	        	
	            byte[] bytes = file.getBytes();
	            
	            try{
	                 File lOutFile = new File(uri);
	                 FileOutputStream lFileOutputStream = new FileOutputStream(lOutFile);
	                 lFileOutputStream.write(bytes);
	                 lFileOutputStream.close();
	                 ePService.regist(vo);
	                 
	            }catch(IOException ie){
	            	
	                //Exception 처리
	                System.err.println("File writing error! ");
	            }
	            System.err.println("File upload success! ");
	        }else{
	            System.err.println("File type error! ");
	        }
	    }
	 
	  
	    return null;
	  }		
}
